package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.demo.entity.User;
import com.example.demo.entity.vo.UserVO;
import com.example.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping()
    public Map<String, Object> login(@RequestParam String username, @RequestParam String password) {
        User currentUser = userService.findUserByUsername(username);
        Map<String, Object> result = new HashMap<>();
        if (null == currentUser) {
            result.put("code", 400);
            result.put("message", "账号或密码错误。");
            return result;
        }
        String encPass = SecureUtil.md5(username + password);
        System.err.println(encPass);
        if (StrUtil.equals(encPass, currentUser.getUserPassword())) {
            UserVO vo = userService.findUserWithRoleByUserId(currentUser.getUserId());
            result.put("code", 200);
            result.put("message", "欢迎" + vo.getUserAge() + "岁的 " + vo.getRoleName() + ",[" + username + "]。");
        } else {
            result.put("code", 400);
            result.put("message", "账号或密码错误。");
        }
        return result;
    }
}
